package com.yingxin.yx.framework.jwt;



import com.yingxin.yx.framework.commons.helper.PropertiesHelper;
import com.yingxin.yx.framework.encrpty.EncryptConst;
import com.yingxin.yx.framework.user.core.IUserSupport;
import com.yingxin.yx.framework.user.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fanchao
 */
@Component
public class JwtTokenPairFactory {


    @Autowired
    private IUserSupport userSupport;

    /**
     * 创建token
     */
    public JwtTokenPair create(UserDto user) {
        UserDto oldUser = userSupport.getUser(user.getUserId());
        if (oldUser != null) {
            user.setJwtPrivateKey(oldUser.getJwtPrivateKey());
        }
        addJwtPrivateKey(user);
        String tokenExpire = PropertiesHelper.getInstance().getProperty(JwtConst.TOKEN_EXPIRE);
        String refreshTokenExpire = PropertiesHelper.getInstance().getProperty(JwtConst.REFRESH_TOKEN_EXPIRE);
        // 生成 tokenPair
        JwtTokenPair tokenPair = JwtFactory.createTokenPair(user.getUserId(), "", "",
                user.getJwtPrivateKey(), Integer.valueOf(tokenExpire), Integer.valueOf(refreshTokenExpire));
        // 保存 user 到缓存
        userSupport.putUser(user);
        return tokenPair;
    }

    /**
     * 创建开放接口 token
     * @param user
     * @return
     */
    public JwtTokenPair createOpenApiToken(UserDto user) {
        UserDto oldUser = userSupport.getUser(user.getUserId());
        if (oldUser != null) {
            user.setJwtPrivateKey(oldUser.getJwtPrivateKey());
        }
        addJwtPrivateKey(user);
        String tokenExpire = PropertiesHelper.getInstance().getProperty(JwtConst.TOKEN_EXPIRE);
        String refreshTokenExpire = PropertiesHelper.getInstance().getProperty(JwtConst.REFRESH_TOKEN_EXPIRE);
        // 生成 tokenPair
        JwtTokenPair tokenPair = JwtFactory.createTokenPair(user.getUserId(), "", "",
                user.getJwtPrivateKey(), Integer.valueOf(tokenExpire), Integer.valueOf(refreshTokenExpire));
        // 保存 user 到缓存
        userSupport.putUser(user);
        return tokenPair;
    }

    /**
     * 添加 secret
     * JwtTokenPair 是 包含accessToken 和 refreshToken
     * JwtPayload 是 accessToken 的负载
     * JwtAuthenticationToken 是 shiro 的 token
     * userDto 是 user 和 jwt 的结合
     */
    public void addJwtPrivateKey(UserDto user) {
        // 配置文件读取 saltSize
        String saltSize = PropertiesHelper.getInstance().getProperty(EncryptConst.SALT_SIZE);
        // 生成一个 secret，该 secret 用来加密 jwt
        String secret = PrivateKeyTool.getSalt(user.getUsername(), Integer.valueOf(saltSize));
        // userDto
        user.setJwtPrivateKey(secret);
    }

}